package cn.sdhuijin.mediaplatform.service;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import cn.sdhuijin.mediaplatform.utils.DirMaker;
import cn.sdhuijin.mediaplatform.utils.FTPClientUtil;

/**
 * @author sunp@sdhuijin.cn:
 * @version 创建时间：2015年3月27日 下午1:54:10 类说明
 */
public class SynService {

	private String videoDirPath = "/playlist/video";
	private String txtDirPath = "/playlist/txt";
	private String localVideoDirPath = Environment
			.getExternalStorageDirectory().getPath() + "/playlist/video";
	private String localTxtDirPath = Environment.getExternalStorageDirectory()
			.getPath() + "/playlist/txt";
	private String[] remountList;
	private String[] localList;
	SharedPreferences sp;
	private Context context;
	private ProgressDialog progressDialog = null;
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				progressDialog = ProgressDialog.show(context, "请稍等...",
						"获取数据中...", true);
				break;
			case 2:
				progressDialog.dismiss();
				break;
			default:
				break;
			}
		};
	};

	public void onStart(Context context) {
		this.context = context;
		sp = context.getSharedPreferences(
				"cn.sdhuijin.mediaplatform_preferences", Context.MODE_PRIVATE);
		mHandler.sendEmptyMessage(1);
		new Thread(downloadRun).start();
	}

	Runnable downloadRun = new Runnable() {
		@Override
		public void run() {
			downloadContent();
		}
	};

	/**
	 * 下载播放内容
	 */
	public void downloadContent() {
		String ftpIp = sp.getString("edt_ip", "");
		int ftpPort = Integer.parseInt(sp.getString("edt_port", "21"));
		String ftpUser = sp.getString("edt_user", "");
		String ftpPWD = sp.getString("edt_pwd", "");

		Log.e("IP", "ip:" + ftpIp);
		Log.e("IP", "port:" + ftpPort);
		Log.e("IP", "user:" + ftpUser);
		Log.e("IP", "pwd:" + ftpPWD);

		File localVideoDir = new File(localVideoDirPath);
		File localTxtDir = new File(localTxtDirPath + "/lilv.txt");
		DirMaker.makeDir(localVideoDir);
		DirMaker.createFile(localTxtDir);
		FTPClientUtil ftpClient = new FTPClientUtil(ftpIp, ftpPort, ftpUser,
				ftpPWD, true, true, "GBK");
		try {
			remountList = ftpClient.listNames(videoDirPath);
		} catch (Exception e) {
			e.printStackTrace();
			Log.e("FTP Error", "连接失败" + e.getMessage());
			mHandler.sendEmptyMessage(2);
			return;
		}

		try {
			if (ftpClient.isExist(txtDirPath + "/lilv.txt")) {
				File currentTxtFile = new File(localTxtDirPath
						+ "/lilv.txt.tmp");
				DirMaker.createFile(currentTxtFile);
				Boolean result = ftpClient.get(txtDirPath + "/lilv.txt",
						localTxtDirPath + "/lilv.txt.tmp");
				if (result) {
					Log.i("FTP下载文件", "利率文件下载成功");
					currentTxtFile.renameTo(new File(localTxtDirPath
							+ "/lilv.txt"));
				} else {
					Log.i("FTP下载文件", "利率文件下载失败");
					DirMaker.deleteFile(localVideoDirPath + "/lilv.txt.tmp");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			Log.e("利率文件异常", "异常信息：" + e.getMessage());
		}

		localList = localList(localVideoDirPath);
		List<String> dif = compareArray(remountList, localList);
		if (dif.size() > 0) {
			for (String str : dif) {
				try {
					File currentFile = new File(localVideoDirPath + "/" + str
							+ ".tmp");
					DirMaker.createFile(currentFile);
					Boolean result = ftpClient.get(videoDirPath + "/" + str,
							localVideoDirPath + "/" + str + ".tmp");
					if (result) {
						Log.i("FTP下载文件", str + "下载成功");
						currentFile.renameTo(new File(localVideoDirPath + "/"
								+ str));
					} else {
						Log.i("FTP下载文件", str + "下载失败");
						DirMaker.deleteFile(localVideoDirPath + "/" + str
								+ ".tmp");
					}
				} catch (Exception e) {
					e.printStackTrace();
					Log.i("FTP下载文件", str + "下载失败" + e.getMessage());
					DirMaker.deleteFile(localVideoDirPath + "/" + str + ".tmp");
				}
			}
		}
		mHandler.sendEmptyMessage(2);
	}

	public String[] localList(String localPath) {
		File file = new File(localPath);
		DirMaker.makeDir(file);
		String[] listNames = file.list();
		return listNames;
	}

	public boolean isNotNull(String[] str) {
		if (str != null && str.length > 0) {
			return true;
		} else {
			return false;
		}
	}

	public List<String> compareArray(String[] remount, String[] local) {
		List<String> al = new ArrayList<String>();
		if (!isNotNull(remount)) {
		} else if (!isNotNull(local)) {
			al = Arrays.asList(remount);
		} else {
			for (String str : remount) {
				if (Arrays.binarySearch(local, str) < 0) {
					Log.i("FTP文件比较", "不同的文件:" + str);
					al.add(str);
				}
			}
		}
		return al;
	}
}
